package com.deli.controller;

import com.alibaba.fastjson.JSON;
import com.deli.entity.ResultDo;
import com.deli.entity.TestResult;
import com.deli.service.AdminService;
import com.deli.service.TestResultService;
import com.deli.utils.ParamUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 查出结果
 */
@RestController
public class TestResultController {

    private static final Logger logger = LoggerFactory.getLogger(TestResultController.class);

    @Autowired
    private TestResultService testResultService;
    @Autowired
    private AdminService adminService;

    /**
     * 进入答题
     * userName 用户名
     * phoneNum 手机号
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "question/get")
    public String login(HttpServletRequest request) {
        ResultDo<String> resultDo = new ResultDo<>();

        try {
            String userName = request.getParameter("userName");
            String phoneNum = request.getParameter("phoneNum");
            LinkedHashMap<String, Object> map = testResultService.getStatusAndQuestionByNameAndPhone(userName, phoneNum);
            resultDo.setSuccess(true);
            resultDo.setData(JSON.toJSONString(map));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            resultDo.setSuccess(false);
            resultDo.setErrorDescription(e.getMessage());
        }
        return JSON.toJSONString(resultDo);
    }

    /**
     * 提交结果
     * userName 用户名
     * phoneNum 手机号
     * answer   答案的json字符串
     *
     * @return
     */
    @RequestMapping(value = "answer/submit")
    public String resultSubmit(@RequestBody TestResult testResult, HttpServletRequest request) {
        ResultDo<String> resultDo = new ResultDo<>();//结果集
        try {
            String userName = ParamUtil.checkParam(testResult.getUserName(), "userName");
            String phoneNum = ParamUtil.checkParam(testResult.getMobilePhone(), "phoneNum");
            String answer = ParamUtil.checkParam(testResult.getAnswer(), "answer");
            String breakTime = ParamUtil.checkParam(testResult.getBreakTime(), "breakTime");
            String testType = ParamUtil.checkParam(testResult.getTestType(), "testType");
            testResultService.resultSubmit(userName, phoneNum, answer, Integer.parseInt(testType), Long.parseLong(breakTime));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            resultDo.setSuccess(false);
            resultDo.setErrorDescription("提交答案:" + e.getMessage());
        } finally {
            return JSON.toJSONString(resultDo);
        }


    }

    /**
     * 显示列表(后台)
     * userName      姓名
     * departmentname 部门
     * mobilePhone 手机号
     * textfield 花名
     * userPosition 岗位
     * testType 测评类型
     * managername 直接上级名字
     * startDateTime 开始时间
     * endDateTime   结束时间
     * pageNum 当前页
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "resultList/show")
    public String resultShow(@RequestBody TestResult testResult,
                             HttpServletRequest request) {
        ResultDo<String> resultDo = new ResultDo<>();
        try {

            String workCode = ParamUtil.checkParam(request.getParameter("workCode"), "workCode");
            //判断是否是管理员
            adminService.findByExemple(workCode);
            //参数
            String userName = testResult.getUserName();
            String departmentname = testResult.getDepartmentname();
            String mobilePhone = testResult.getMobilePhone();
            String textfield = testResult.getTextfield();
            String userPosition = testResult.getUserPosition();
            Integer testType = Integer.parseInt(testResult.getTestType().toString());
            String managername = testResult.getManagername();

            Long startDateTime = Long.valueOf(request.getParameter("startDateTime"));
            Long endDateTime = Long.valueOf(request.getParameter("endDateTime"));
            Integer pageNum = Integer.parseInt(request.getParameter("pageNum"));
            List<LinkedHashMap<String, Object>> dataList = testResultService.getExport(userName, departmentname, mobilePhone, textfield, userPosition, testType, managername, startDateTime, endDateTime, pageNum);
            int totaldataCount = Integer.parseInt(dataList.get(0).get("totaldataCount").toString());
            dataList.get(0).remove("totaldataCount");
            resultDo.setData(JSON.toJSONString(dataList));
            resultDo.setTotaldataCount(totaldataCount);

            //页数
            if (totaldataCount <= 10) {
                resultDo.setTotalPageCount(1);
            } else {
                double pages = totaldataCount / 1.0 / 10.0;
                int pageCount = (int) Math.ceil(pages);
                resultDo.setTotalPageCount(pageCount);
            }
            resultDo.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            resultDo.setSuccess(false);
            resultDo.setErrorDescription(e.getMessage());
        } finally {
            return JSON.toJSONString(resultDo);
        }
    }


    /**
     * 显示结果详情
     * id 记录id
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "resultDetail/show")
    public String resultDetailShow(HttpServletRequest request) {
        ResultDo<String> resultDo = new ResultDo<>();
        try {
            Long id = Long.parseLong(request.getParameter("recordId"));
            HashMap<String, String> data = testResultService.getResultById(id);//通过id获得result字符串
            resultDo.setData(JSON.toJSONString(data));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询结果详情：" + e.getMessage());
            resultDo.setSuccess(false);
            resultDo.setErrorDescription("查询结果详情：" + e.getMessage());
        } finally {
            return JSON.toJSONString(resultDo);
        }
    }

    /**
     * 点击获得性格分析的解释(180的)
     * characterName 性格名
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "character/analysis")
    public String characterAnalysisShow(HttpServletRequest request) {
        ResultDo<String> resultDo = new ResultDo<>();

        String data = "";

        try {
            String characterName = ParamUtil.checkParam(request.getParameter("characterName"), "characterName");
            HashMap<String, String> map = testResultService.characterAnalysisShow(characterName);
            resultDo.setSuccess(true);
            resultDo.setData(JSON.toJSONString(map));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            resultDo.setSuccess(false);
            resultDo.setErrorDescription("在查询性格详情时发生异常：" + e.getMessage());
        } finally {
            return JSON.toJSONString(resultDo);
        }
    }
}